package helpers;

import interfaces.*;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.*;

import automaton.*;

public class FileOperations {
	/**
	 * Get automata from txt file
	 * @param fileName
	 * @return
	 */
	@SuppressWarnings({ "resource", "unchecked" })
	public static DFA readFile(String fileName){
		try
		{
			
			BufferedReader reader = new BufferedReader(new FileReader(fileName));
			List<Transition<String>> listTrans = new ArrayList<Transition<String>>();
			
			HashMap<String, State> listState = new HashMap<String, State>();
			
			String line = null;
			while((line = reader.readLine())!=null){
				if(line.compareTo("") != 0 && !line.contains("//")){
					String[] arrString = line.split("\\|");
					
					if(arrString[0]!=null){
						State s = listState.get(arrString[0].trim());
						
						if(s == null){	
							s = new StateImpl(arrString[0].trim(),
												arrString[1].trim().compareTo("")==0 ? false: true,
													arrString[2].trim().compareTo("")==0 ? false: true);
							listState.put(s.label().toString(), s);							
						}else{
							((StateImpl)s).setInitial(arrString[1].trim().compareTo("")==0? false: true);
							((StateImpl)s).setTerminal(arrString[2].trim().compareTo("")==0? false: true);
						}
						if(arrString.length > 3){
							String[] arrTrans = arrString[3].trim().split(",");							
							for(int j = 0 ; j < arrTrans.length;j++){
								String tran = arrTrans[j].trim();
								if(tran.compareTo("")!=0){
									String lbl = tran.substring(0,1);
									String target = tran.substring(2, tran.length());
									State t = listState.get(target); 
									if(t == null){
										t = new StateImpl(target, false, false);
										listState.put(target, t);
									}
									listTrans.add(new TransitionImpl<String>(s, t, lbl));
								}else{
									listTrans.add(new TransitionImpl<String>(s, null, null));
								}
							}
						}else{
							listTrans.add(new TransitionImpl<String>(s, null, null));
						}
					}
				}					
					
			}
			
			Transition<String>[] result = new TransitionImpl[listTrans.size()];
			listTrans.toArray(result);
			DFA automata = new DFA(result);
			
			return automata;
		}
		catch(Exception e){
			System.out.println("Data input is wrong !");
			return null;
		}
	}
	
	/**
	 * 
	 * @param path
	 * @param content
	 */
	public static void saveFile(String path, String content)
	{
		try {
            FileWriter fw = new FileWriter(path);
            
            fw.write(content);
            fw.close();
        } 
		catch (FileNotFoundException fEx)
        {
        	System.out.println(fEx.getMessage());
        }
		catch (Exception e) {
            System.out.println("Saving failed!!!");
        }
	}
}
